package x.ovo.wechat.bot.plugin.push;

import java.io.IOException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;

/**
 * Author: wxy97.com
 * Date: 2024/9/30 11:29
 * Description:
 */
@Slf4j(topic = "TelegramPushStrategy")
public class TelegramPushStrategy implements PushStrategy {

    @Override
    public void push(Map<String, ?> config, OkHttpClient client, String flag, String content) {
        String accessToken = String.valueOf(config.get("telegram_token"));
        String chatId = String.valueOf(config.get("telegram_chat_id"));
        String telegramHost = String.valueOf(config.get("telegram_host"));

        JSONObject json = JSONUtil.ofObj()
            .set("chat_id", chatId)
            .set("text", flag + "\n" + content);
        Request request = new Request.Builder()
            .url(telegramHost + accessToken + "/sendMessage")
            .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
            .build();
        try (Response response = client.newCall(request).execute()) {
            JSONObject object = JSONUtil.parseObj(response.body().string());
            if (object.getBool("ok")) {
                log.info("Telegram推送成功");
            } else {
                log.error("Telegram推送失败");
            }
        } catch (IOException e) {
            log.error("Telegram推送失败: {}", e.getMessage());
        }
    }
}
